package com.example.capsule.service;

import com.example.capsule.entity.User;
import com.example.capsule.repository.UserRepository;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.Optional;

@Service
public class UserService {

    private final UserRepository userRepository;

    @Value("${jwt.secret:defaultSecretKey}")
    private String jwtSecret;

    @Value("${jwt.expiration:86400000}") // 24小时
    private long jwtExpiration;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    /**
     * 生成JWT token
     */
    public String generateToken(User user) {
        return Jwts.builder()
                .setSubject(user.getPhone())
                .claim("userId", user.getId())
                .claim("phone", user.getPhone())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + jwtExpiration))
                .signWith(SignatureAlgorithm.HS512, jwtSecret)
                .compact();
    }

    /**
     * 验证JWT token有效性 - 修正这个方法
     */
    public boolean validateToken(String token) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(jwtSecret)
                    .parseClaimsJws(token)
                    .getBody();

            // 检查token是否过期
            return !claims.getExpiration().before(new Date());
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 从token中获取手机号 - 修正这个方法
     */
    public String getPhoneFromToken(String token) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(jwtSecret)
                    .parseClaimsJws(token)
                    .getBody();

            return claims.getSubject(); // subject中存储的是手机号
        } catch (Exception e) {
            throw new RuntimeException("Invalid token", e);
        }
    }

    /**
     * 手机号登录或注册
     */
    public String loginOrRegister(String phone) {
        // 查找用户
        Optional<User> userOptional = userRepository.findByPhone(phone);
        User user;

        if (userOptional.isPresent()) {
            user = userOptional.get();
        } else {
            // 创建新用户
            user = new User();
            user.setPhone(phone);
            user.setNickname("用户" + phone.substring(phone.length() - 4));
            user = userRepository.save(user);
        }

        // 生成JWT token
        return generateToken(user);
    }

    /**
     * 根据手机号查找用户
     */
    public Optional<User> findByPhone(String phone) {
        return userRepository.findByPhone(phone);
    }

    /**
     * 保存用户
     */
    public User save(User user) {
        return userRepository.save(user);
    }
}